import Vue from 'vue'
import Vuex from 'vuex'
// 先 npm install vuex@3.6.2
Vue.use(Vuex)
const store = new Vuex.Store({
  // 存储的对象
  state: {
    loginState:false,
    user:{
      userId:0,
      userNickName:'aaa',
    },
    mall_token:''
  },
  // state数据修改
  mutations: {
    setUserState (state,user) {
      store.state.loginState = true;// 登录状态为true
      store.state.user = user;// 用户的信息
      localStorage.setItem("mall_token",user.token);// 持久化保持用户token
    },
    removeUserState(state){
      store.state.loginState = false;// 登录状态为false
      store.state.user = { // 还原user
        userId:0,
        userNickName:'aaa'
      };// 用户的信息
      localStorage.removeItem("mall_token")// 持久化保持用户token
    }
  },
  // 发起动作，写业务代码
  actions: {
    login (context,user) {
      if(user){
        context.commit('setUserState',user);
      }
    },
    loginOut(context){
      context.commit("removeUserState")
    }
  }
})
export default store
